//
//  CollectionEditImageCell.swift
//  CooperSwift_Example
//
//  Created by 计海峰 on 2021/12/13.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift
import ZLPhotoBrowser

// 默认实现一个

// 控制器
open class EditImageControlModel: NSObject, ViewControlProtocol, BindKeyProtocol {  }

/// 默认 cv 控制器
open class CollectionEditImageCVCModel: NSObject, CollectionCellLongPressConfigProtocol, BindKeyProtocol {
    
    public func cellCls() -> UICollectionViewCell.Type {
        return CollectionEditImageCVC.self
    }
    
    /// EditImageControlModel
    public var model: Any?
    
    /// EditImageControlModel
    required public init(_ model: Any?) {
        super.init()
        self.model = model
        self.cellSize = CGSize((Screen.width - 32)/3.0 - 0.2, (Screen.width - 32)/3.0 - 0.2)
    }
    
    /// 多次加载
    @MainActor func every(_ imageV: UIImageView, deleteBT: UIButton, cell: UICollectionViewCell) {
        guard let info = self.model as? EditImageControlModel else { return }
        info.loadAll(imageV, judgeType: true)
        if info.imageName != nil {
            deleteBT.isHidden = true
        }else {
            deleteBT.isHidden = false
        }
    }
    
    /// 一次配置
    func configDown(_ imageV: UIImageView, deleteBT: UIButton, cell: UICollectionViewCell) {
        
    }
    
}

/// 默认 cvc cell 
open class CollectionEditImageCVC: UICollectionViewCell {
    
    let disposeBag = DisposeBag()
    
    let imageV = UIImageView.init(frame: .zero).then {
        $0.contentMode = .scaleAspectFill
        $0.layer.masksToBounds = true
        $0.image = .init(named: "icon_item_image_add")
        $0.isUserInteractionEnabled = true
    }
    let deleteBT = UIButton.init(frame: .zero).then {
        $0.setImage(.init(named: "icon_item_image_delete"), for: .normal)
    }
    
    //MARK: -  初始化
    override init(frame: CGRect) {
        super.init(frame: frame)
        layoutViews()
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    open override func bindTo(_ info: Any?) {
        self.info = info
        every()
    }
    
    //MARK: -
    func takePhoto() {
        guard let cellModel = self.info as? CollectionEditImageCVCModel else { return }
        ZLPhotoConfiguration.default().allowSelectImage = true
        ZLPhotoConfiguration.default().allowSelectVideo = false
        let ps = ZLPhotoPreviewSheet()
        ps.selectImageBlock = { [weak self] (images, isOriginal) in
            // your code
            guard let cell = self else { return }
            guard let info = cell.info as? CollectionEditImageCVCModel else { return }
            images.forEach { image in
                let imageControl = EditImageControlModel().then {
                    $0.imageSource = image.image
                }
                // cvcModle.addTargetKey(cvcModle.bindKey(DisposeBag()), isTarget: true)
                let cvcModle = CollectionEditImageCVCModel.init(imageControl)
                cvcModle.addTargetKey(cellModel.targetKey, isTarget: true)
                info.postCollectionService(.insertItemLast((0, 1)), info: cvcModle, targetKey: info.targetKey)
            }
        }
        guard let vc = UIApplication.currentVC() else { return }
        ps.showPhotoLibrary(sender: vc)
    }
    
    func showPhoto(_ image: UIImage) {
        showPhotosBrowser([image])
    }
    
    // 操作
    func operationPhoto() {
        guard let cellModel = self.info as? CollectionEditImageCVCModel else { return }
        guard let info = cellModel.model as? EditImageControlModel else { return }
        if info.imageName != nil {
            takePhoto()
        }else {
            cellModel.post("showImages", info: cellModel)
        }
    }
    
    //MARK: - 加载图片
    func every() {
        guard let cellModel = self.info as? CollectionEditImageCVCModel else { return }
        // 执行一次配置
        if !cellModel.isConfigDone {
            cellModel.isConfigDone = true
            cellModel.configDown(imageV, deleteBT: deleteBT, cell: self)
        }
        cellModel.every(imageV, deleteBT: deleteBT, cell: self)
    }
    
    //MARK: - 写布局
    func layoutViews() {
        contentView.addSubview(imageV)
        imageV.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
        contentView.addSubview(deleteBT)
        deleteBT.snp.makeConstraints { make in
            make.top.right.equalToSuperview().offset(0)
            make.width.height.equalTo(16)
        }
        
        let tap = UITapGestureRecognizer()
        imageV.addGestureRecognizer(tap)
        imageV.isUserInteractionEnabled = true
        tap.rx.event.subscribe(onNext: { [weak self] _ in
            self?.operationPhoto()
        }).disposed(by: disposeBag)
        
        deleteBT.addTarget(self, action: #selector(deleteItem), for: .touchUpInside)
    }
    
    @objc func deleteItem() {
        guard let cellModel = self.info as? CollectionEditImageCVCModel else { return }
        cellModel.postCollectionService(.removeItem)
    }
    
}
